package com.lyw.GeoLocationClient.service;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import retrofit.ErrorHandler;
import retrofit.RetrofitError;

import java.net.SocketTimeoutException;


public class RetrofitErrorHandler implements ErrorHandler {
    Context context;
    String TAG = "RetrofitErrorHandler";

    public static final String RETROFIT_ERROR_TIMEOUT = "timeout";
    public static final String RETROFIT_ERROR_CONNECTION = "connection";
    public static final String RETROFIT_ERROR_UNKNOWN = "unknown";

    public RetrofitErrorHandler(Context context) {
        this.context = context;
    }

    @Override
    public Throwable handleError(RetrofitError cause) {
        cause.printStackTrace();
        if (cause.getKind() == RetrofitError.Kind.NETWORK) {
            if (cause.getCause() instanceof SocketTimeoutException) {
                Log.d(TAG, "Timeout Error: " + cause.getResponse());
                Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_TIMEOUT());
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            } else {
                Log.d(TAG, "Connection Error: " + cause.getResponse());
                Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION());
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            }
        } else {
            Log.d(TAG, "Unknown Error: " );
            Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_UNKNOWN());
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        }
        return cause;
    }
}